<?php
/**
 * Created by Benjamin.
 * Date: 2020/5/8
 * Time: 18:32
 */
namespace App\Process;

use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\EasySwoole\ServerManager;
use Swoole\Process;
use EasySwoole\EasySwoole\Config;
class Consumer extends AbstractProcess
{
    private $isRun = false;
    public function run($arg)
    {
        // TODO: Implement run() method.
       $this->addTick(20,function (){
            if(!$this->isRun){
                $this->isRun = true;
                $redisPool = \EasySwoole\RedisPool\Redis::getInstance()->get('redis');
                $redis = $redisPool->getObj();
                while (true){
                    try{
                        $msg = $redis->lPop('privite_chat'.Config::getInstance()->getConf('APP.CURRENT.host'));
                        if( $msg){
                            echo '收到跨区消息'.PHP_EOL;
                            // do you task
                            $msgArr =  json_decode( $msg,true);
                            $userInfoJson = $redis->hGet(Config::getInstance()->getConf('CHAT.online_user').Config::getInstance()->getConf('APP.CURRENT.host'),$msgArr['user_id']);
                            $userInfoArr = json_decode( $userInfoJson,true);
                            $server = ServerManager::getInstance()->getSwooleServer();
                            $info = $server->getClientInfo($userInfoArr['fd']);

                            if ($info && $info['websocket_status'] == WEBSOCKET_STATUS_FRAME) {
                                $server->push($userInfoArr['fd'], '消息'.$msgArr['content'] .  ' at ' . date('H:i:s'));
                                echo '推送成功，fd='.$userInfoArr['fd'];
                            }
                        }else{
                         //   echo '没有跨区消息'.PHP_EOL;
                            break;
                        }
                    }catch (\Throwable $throwable){
                        break;
                    }
                }
                $this->isRun = false;
                $redisPool->recycleObj($redis);
            }
        });

    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}